<template>
  <div class="text-list">
    <van-pull-refresh v-model="refreshing" :success-text="refreshText" @refresh="onRefresh" :success-duration="1500">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error" error-text="请求失败，点击重新加载">
        <text-item v-for="item in list" :key="item.art_id" :text="item"></text-item>
        <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { channelText } from '@/api/channel'
import textItem from '@/components/text-item/index.vue'
export default {
  props: {
    channel: {
      type: Object,
      require: true
    }
  },
  components: {
    textItem
  },
  data () {
    return {
      list: [],
      // 控制数据加载效果
      loading: false,
      // 控制数据加载完成
      finished: false,
      // 控制下拉刷新状态
      refreshing: false,
      // 控制数据加载失败
      error: false,
      // 下拉刷新文本
      refreshText: '刷新成功',
      timestamp: null
    }
  },
  methods: {
    // 触底 发起 axios 请求 loading = true 加载中； 加载完成之后 需要将 loading = false
    async onLoad () {
      // 1. 发起 axios 异步请求
      try {
        const { data: res } = await channelText({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        })
        // console.log(res, 111)
        // 模拟出错
        // if (Math.random() > 0.5) {
        //   JSON.parse('ghjk')
        // }
        const { results } = res.data
        this.list.push(...results)
        // 2. 加载状态结束
        this.loading = false
        // 3. 数据全部加载完成 返回数据为空 走 else finished = true 关闭请求
        if (results.length) {
          this.timestamp = res.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        // 列表数据加载失败，error = true 展示错误，点击重新触发 load
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      // 1. 发起数据请求
      try {
        const { data: res } = await channelText({
          channel_id: this.channel.id,
          timestamp: Date.now()
        })
        // 模拟出错
        // if (Math.random() > 0.5) {
        //   JSON.parse('ghjk')
        // }
        // 2. 将数据添加到列表头部
        const { results } = res.data
        this.list.unshift(...results)
        // 3. 关闭刷新
        this.refreshText = `刷新成功,共加载${results.length}条数据`
        this.refreshing = false
      } catch (err) {
        this.refreshText = '刷新失败'
        this.refreshing = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.text-list {
  // height: 100%;
  height: 79vh;
  overflow: auto;
}
</style>
